package com.ct.boss.demo.controller;

import com.ct.boss.demo.http.HttpResult;
import com.ct.boss.demo.model.SysUser;
import com.ct.boss.demo.service.UserService;
import com.ct.boss.demo.utils.TokenUtil;
import com.ct.boss.demo.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author ChenTong
 * @version 1.0
 * @description 登录逻辑控制器
 * @date 2020/6/15 7:47
 * @modified
 **/
@Validated
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public HttpResult login(@RequestBody @Valid LoginVO user, HttpServletResponse response){
        SysUser sysUser = new SysUser();
        sysUser.setPassword(user.getPassword());
        sysUser.setUsername(user.getUsername());
        SysUser realUser = userService.login(sysUser);
        //新建token
        String token = TokenUtil.createJwtToken(sysUser.getUsername(),5000000);
        //将token信息添加到响应头中方便前端存放以及获取
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.setHeader("Authorization",token);

        return HttpResult.ok(realUser);
    }
}
